/* Write a program like cp that, when used to copy a regular file that contains holes
   (sequences of null bytes), also creates corresponding holes in the target file. */

/* How to create file with hole
 * dd if=/dev/urandom bs=4096 count=2 of=file_with_holes
 * dd if=/dev/urandom bs=4096 seek=7 count=2 of=file_with_holes
*/

/*
 * To check file hole
 * xxd -b <file>
*/

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

static const size_t buffer_size = 4096; /* page size? */

int
main (int argc, char *argv[])
{
  if (argc != 3) fputs ("Missing argument", stderr), _exit (EXIT_FAILURE);
  int file_in, file_out;
  file_out = open (argv[1], O_WRONLY|O_CREAT|O_TRUNC,
                  S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
  file_in = open (argv[2], O_RDONLY);
  if (file_in == -1 || file_out == -1)
    fputs ("Unable to open/create file", stderr), _exit (EXIT_FAILURE);

  char buffer[buffer_size];
  ssize_t nbytes_read = 0;
  while ((nbytes_read = read (file_in, buffer, buffer_size)) > 0)
    {
      if (write (file_out, buffer, nbytes_read) != nbytes_read)
        {
          exit (EXIT_FAILURE);
        }
    }
  close (file_in);
  close (file_out);

  return EXIT_SUCCESS;
}
